const express = require('express');
const router = express.Router();
const userManagementService = require('../../services/userManagementService');
const adminAuth = require('../../middleware/adminAuth');
const { checkPermission } = require('../../middleware/permission');

/**
 * 获取用户列表
 */
router.get('/', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      search,
      status,
      memberLevel,
      startDate,
      endDate,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = req.query;

    const result = await userManagementService.getUserList({
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      status: status !== undefined ? parseInt(status) : undefined,
      memberLevel,
      startDate,
      endDate,
      sortBy,
      sortOrder
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error.message
    });
  }
});

/**
 * 获取用户详情
 */
router.get('/:id', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const result = await userManagementService.getUserById(userId);

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(404).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 更新用户信息
 */
router.put('/:id', adminAuth, checkPermission('user', 'update'), async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const { nickname, phone, status, memberLevel, avatar, gender } = req.body;

    await userManagementService.updateUser(userId, {
      nickname,
      phone,
      status,
      memberLevel,
      avatar,
      gender
    }, req.adminId);

    res.json({
      success: true,
      message: '用户信息更新成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 调整用户积分
 */
router.post('/:id/points', adminAuth, checkPermission('user', 'points'), async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const { amount, reason } = req.body;

    if (!amount || amount === 0) {
      return res.status(400).json({
        success: false,
        message: '积分调整数量不能为空或为0'
      });
    }

    const result = await userManagementService.adjustUserPoints(
      userId, 
      parseInt(amount), 
      reason, 
      req.adminId
    );

    res.json({
      success: true,
      message: '积分调整成功',
      data: result
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 重置用户密码
 */
router.put('/:id/password', adminAuth, checkPermission('user', 'update'), async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const { newPassword } = req.body;

    if (!newPassword) {
      return res.status(400).json({
        success: false,
        message: '新密码不能为空'
      });
    }

    if (newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度不能少于6位'
      });
    }

    await userManagementService.resetUserPassword(userId, newPassword, req.adminId);

    res.json({
      success: true,
      message: '密码重置成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 获取用户标签
 */
router.get('/:id/tags', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const tags = await userManagementService.getUserTags(userId);

    res.json({
      success: true,
      data: tags
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户标签失败',
      error: error.message
    });
  }
});

/**
 * 获取用户行为分析
 */
router.get('/:id/behavior', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const userId = parseInt(req.params.id);
    const { days = 30 } = req.query;

    const analysis = await userManagementService.getUserBehaviorAnalysis(
      userId, 
      parseInt(days)
    );

    res.json({
      success: true,
      data: analysis
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户行为分析失败',
      error: error.message
    });
  }
});

/**
 * 用户分群分析
 */
router.get('/analytics/segmentation', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const segmentation = await userManagementService.getUserSegmentation();

    res.json({
      success: true,
      data: segmentation
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户分群分析失败',
      error: error.message
    });
  }
});

/**
 * 批量更新用户
 */
router.put('/batch', adminAuth, checkPermission('user', 'update'), async (req, res) => {
  try {
    const { userIds, updateData } = req.body;

    if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '用户ID列表不能为空'
      });
    }

    await userManagementService.batchUpdateUsers(userIds, updateData, req.adminId);

    res.json({
      success: true,
      message: `成功更新 ${userIds.length} 个用户`
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 导出用户数据
 */
router.get('/export/excel', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const {
      search,
      status,
      memberLevel,
      startDate,
      endDate
    } = req.query;

    const exportData = await userManagementService.exportUsers({
      search,
      status: status !== undefined ? parseInt(status) : undefined,
      memberLevel,
      startDate,
      endDate
    });

    // 设置响应头
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Content-Disposition', 'attachment; filename=users.json');

    res.json({
      success: true,
      data: exportData,
      message: `导出 ${exportData.length} 条用户数据`
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '导出用户数据失败',
      error: error.message
    });
  }
});

/**
 * 获取用户统计概览
 */
router.get('/analytics/overview', adminAuth, checkPermission('user', 'read'), async (req, res) => {
  try {
    const { User, Order, PointsTransaction } = require('../../models');
    const { Op } = require('sequelize');

    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    const lastWeek = new Date(today);
    lastWeek.setDate(lastWeek.getDate() - 7);

    const lastMonth = new Date(today);
    lastMonth.setMonth(lastMonth.getMonth() - 1);

    const [
      totalUsers,
      todayUsers,
      weekUsers,
      monthUsers,
      activeUsers,
      totalOrders,
      totalPoints
    ] = await Promise.all([
      User.count(),
      User.count({ where: { createdAt: { [Op.gte]: today } } }),
      User.count({ where: { createdAt: { [Op.gte]: lastWeek } } }),
      User.count({ where: { createdAt: { [Op.gte]: lastMonth } } }),
      User.count({ 
        where: { 
          lastLogin: { [Op.gte]: lastWeek }
        } 
      }),
      Order.count(),
      PointsTransaction.sum('amount', { where: { type: 'earn' } }) || 0
    ]);

    res.json({
      success: true,
      data: {
        totalUsers,
        todayUsers,
        weekUsers,
        monthUsers,
        activeUsers,
        totalOrders,
        totalPoints
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户统计概览失败',
      error: error.message
    });
  }
});

module.exports = router;